{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards,ScopedTypeVariables #-}
module Lib.Ajax(ajaxGet_,ajaxGet,ajaxDecodeGet_) where
import Miso
import Miso.String (MisoString,toMisoString)
import Data.ByteString
import Data.Maybe
import Data.Monoid
import Data.Aeson
import JavaScript.Web.XMLHttpRequest

ajaxGet::String -> IO (Maybe ByteString)
ajaxGet url = contents <$> xhrByteString reqInfo
 where
  reqInfo = Request {
    reqMethod = GET
   ,reqURI = toMisoString $ url
   ,reqLogin = Nothing
   ,reqHeaders = []
   ,reqWithCredentials = False
   ,reqData = NoData
 }

ajaxGet_::String -> IO ByteString
ajaxGet_ url = do
    mayString <- ajaxGet url
    case mayString of
        Nothing  -> error $ "fetch " <> url <> "error!"
        Just ctx -> pure ctx


ajaxDecodeGet_::(FromJSON a) => String -> IO a
ajaxDecodeGet_ url = do
  getString <- ajaxGet_ url
  case eitherDecodeStrict getString  of
    Left l -> error $ "decode " <> url <> " error! " <> l
    Right a -> pure a
